package com.ec.web.controller.system;

import com.ec.auth.web.service.TenantRegisterService;
import com.ec.common.constant.I18nConstant;
import com.ec.common.constant.TenantConstants;
import com.ec.common.core.controller.BaseController;
import com.ec.common.core.domain.AjaxResult;
import com.ec.common.core.redis.RedisCache;
import com.ec.common.exception.ServiceException;
import com.ec.common.utils.AssertUtils;
import com.ec.common.utils.CheckUtils;
import com.ec.common.utils.MessageUtils;
import com.ec.common.utils.StringUtils;
import com.ec.saas.dto.TenantDatabaseDTO;
import com.ec.saas.form.TenantRegisterBody;
import com.ec.saas.service.IMasterTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.sql.SQLException;

/**
 * 注册验证
 */
@RestController
public class SysRegisterController extends BaseController {

    //    @Autowired
//    private SysRegisterService registerService;
//
//    @Autowired
//    private ISysConfigService configService;

    @Autowired
    private TenantRegisterService tenantRegisterService;
    //
    @Autowired
    private IMasterTenantService masterTenantService;

    @Autowired
    private RedisCache redisCache;

    @PostMapping("/register")
    public AjaxResult registerTenant(@Valid @RequestBody TenantRegisterBody tenantRegisterBody) {
        AssertUtils.isTrue(!StringUtils.equals(tenantRegisterBody.getAdminPass(),
                tenantRegisterBody.getConfirmPassword()), "密码不一致");
        String captcha = CheckUtils.validateCaptcha(redisCache, tenantRegisterBody.getUuid());
        // 抛出异常校验验证码
        if (captcha == null) return AjaxResult.error(MessageUtils.message(I18nConstant.USER_JCAPTCHA_EXPIRE));
        else if (!tenantRegisterBody.getCode().equalsIgnoreCase(captcha))
            return AjaxResult.error(MessageUtils.message(I18nConstant.USER_JCAPTCHA_ERROR));

        // 校验参数是否合法
        AssertUtils.isTrue(TenantConstants.NOT_UNIQUE.equals(
                        masterTenantService.checkTenantNameUnique(tenantRegisterBody.getTenantName())),
                "注册'" + tenantRegisterBody.getTenantName() + "'失败，账号已存在");

        // 开始注册
        try {
            TenantDatabaseDTO tenantDatabase = tenantRegisterService.initDatabase(tenantRegisterBody);
            return toAjax(masterTenantService.insertMasterTenant(tenantDatabase));
        } catch (SQLException ex) {
            ex.printStackTrace();
            throw new ServiceException("注册'" + tenantRegisterBody.getTenantName() + "'失败，创建租户时发生错误");
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ServiceException("注册'" + tenantRegisterBody.getTenantName() + "'失败，请与我们联系");
        }
    }
}
